<?php
/**
 * Created by PhpStorm.
 * User: yyq
 * Date: 2018/7/4
 * Time: 23:09
 */

namespace Member\Controller;


use Common\Controller\AdminbaseController;
use Common\Model\CardModel;
use Common\Model\MemberModel;
use Common\Model\MemCardModel;
use Common\Model\RecordModel;

class MemberController extends AdminbaseController
{
    private $member_model;
    private $card_model;
    private $mem_card_model;
    private $record_model;

    public function __construct()
    {
        parent::__construct();
        $this->member_model     = new MemberModel();
        $this->card_model       = new CardModel();
        $this->mem_card_model   = new MemCardModel();
        $this->record_model     = new RecordModel();
    }

    public function lists() {
        $where = [];
        if(IS_POST) {
            $phone = I('post.phone');
            $parent = I('post.parent');
            if($phone) {
                $where['a.phone'] = $phone;
            }
            if($parent) {
                $where['a.parent'] = ['like', '%'.$parent.'%'];
            }
        } else {
            $phone = I('get.phone');
            $parent = I('get.parent');
            if($phone) {
                $where['a.phone'] = $phone;
            }
            if($parent) {
                $where['a.parent'] = ['like', '%'.$parent.'%'];
            }
        }

        $count = $this->mem_card_model
            ->alias('a')
            ->join('left join sw_member as b on a.phone = b.phone')
            ->where($where)
            ->count();
        $page = $this->page($count, C("PAGE_NUMBER"));

        $result = $this->mem_card_model
            ->alias('a')
            ->join('left join sw_member as b on a.phone = b.phone')
            ->where($where)
            ->limit($page->firstRow, $page->listRows)
            ->field('a.*, b.openid, nickname')
            ->select();

        $para['list'] = $result;
        $para['Page'] = $page->show();
        $para['formget']    = I('');
        $this->assign($para);
        $this->display();
    }

    public function add() {
        if(IS_POST) {
//            dump(I(''));
            $post = I('post.post');
            $post['times']  = $post['number'];
            if($this->mem_card_model->where(['phone' => $post['phone']])->find()) {
                $this->error('已有该会员');
            }
            if($this->mem_card_model->add($post)) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        } else {

            $this->assign('options', $this->card_model->getTypeOption());
            $this->display();
        }
    }

    public function edit() {
        if(IS_POST) {
            $post = I('post.post');
            if($post['type'] == 'times' && !$post['times']) {
                $this->error('次数卡，请填写剩余次数');
            }
            $this->mem_card_model->save($post);
            $this->success('');
        } else {
            $id = I('get.id');
            $info = $this->mem_card_model->find($id);
            $this->assign('options', $this->card_model->getTypeOption($info['type']));
            $this->assign($info);
            $this->display();
        }
    }

    public function signCard() {
        $card_id = I('get.id');
        $tag     = I('get.tag');
        $card_info = $this->mem_card_model->find($card_id);
        if(!$card_info) {
            exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '未找到会员卡信息'));
        }
        $this->mem_card_model->startTrans();
        $is_commit = true;

        if($card_info['type'] == 'times') {
            if($card_info['times'] == 0) {
                exit($this->returnApiError(ApiBaseController::FATAL_ERROR, '次数卡已用完'));
            }
            if($tag == 'swim') {
                if($this->mem_card_model->where(['id' => $card_id])->save(['times' => ['exp', 'times-1']]) == false) {
                    $is_commit = false;
                }
            } else {
                if($this->mem_card_model->where(['id' => $card_id])->save(['times' => ['exp', 'times-0.5']]) == false) {
                    $is_commit = false;
                }
            }

        }

        if($this->record_model->addOne($card_id, $openid, 'admin', $tag, $card_info['phone']) == false) {
            $is_commit = false;
        }
        if($is_commit) {
            $this->mem_card_model->commit();
            $this->success('');
        } else {
            $this->mem_card_model->rollback();
            $this->error('');
        }
    }

    public function record() {
        $where = [];
        $phone  = I('get.phone');
        $where['phone'] = $phone;
        $count = $this->record_model
            ->where($where)
            ->count();

        $page = $this->page($count, C('PAGE_NUMBER'));
        $result = $this->record_model
            ->where($where)
            ->limit($page->firstRow, $page->listRows)
            ->order('create_time desc')
            ->select();
        $para['list'] = $result;
        $para['Page'] = $page->show();
        $this->assign($para);
        $this->display();
    }

    public function download($url, $path = '/data/uploads/')
    {
        $path = getcwd().$path;
        delFile(getcwd().'/data/uploads');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);//dump(pathinfo($url, PATHINFO_BASENAME));exit;
        $filename = pathinfo($url, PATHINFO_BASENAME);//dump($filename);
        $resource = fopen($path . $filename, 'a');//dump($resource);
        fwrite($resource, $file);//dump($file);
        fclose($resource);
    }

    /**
     *导入用户
     **/
    public function member_add() {
        if(IS_POST) {
            $result = upload_img('excel');//dump($result);exit;
//            $this->download("http://p3pkjxg6h.bkt.clouddn.com/excel/20180208/5a7bed4f1cff4.xlsx");exit;
            if($result) {
//                $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
//                $this->download(setUrl($result[0]));
//                $this->member_import(getcwd().'/data/uploads/'.pathinfo(setUrl($result[0]), PATHINFO_BASENAME), $extension);
                $this->member_import(getcwd().'/data/upload/'.$result[0], pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
            } else {
                $this->error('error');
            }
        } else {
//            $this->assign('url', sp_get_host().'/public/images/模板.xlsx');
            $this->display();
        }
    }

    //导入数据方法
    protected function member_import($filename, $exts='xls') {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel=new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
//            import("simplewind.Library.Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader=new \PHPExcel_Reader_Excel5();
        }else if($exts == 'xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader=new \PHPExcel_Reader_Excel2007();
        }
        //载入文件
        $PHPExcel=$PHPReader->load($filename);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$PHPExcel->getSheet(0);//dump($currentSheet);exit;
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=1;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $data[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
            }

        }
        $this->save_import($data);
    }

    //保存导入数据
    public function save_import($data) {
//        dump($data);
//        exit;
        $this->mem_card_model->startTrans();
        $is_commit = true;
        foreach ($data as $k=>$v){
            if($k >= 2 && $v['A']){
//                dump($v['A'].$v['B'].$v['C']);exit;
                $info[$k-2] = array();
                $info[$k-2]['phone'] = $v['B'];//手机号
                if($this->mem_card_model->where(['parent' => $v['A'], 'phone' => $v['B']])->find()) {
//                    $is_commit = false;
//                    $error .= '用户：'.$v['B'].'已存在';
//                    break;
//                    $user_id = $this->user_model->where(['phone' => $v['B']])->getField('id');//dump($user_id);
                    /*if($this->record_model->addRecord($user_id, $v['C'], '充值赠送', 'in', 'gold_coin') == false) {
                                            $is_commit = false;
                                        }*/
                    /*if($this->record_model->addRecord($user_id, $v['C'], '导入充值', 'in', 'balance') != 1) {
                        $is_commit = false;$error=1;
                    }*/
                } else {
                    $v['C'] = explode('.', $v['C']);//dump($v['C']);
                    $v['C'] = implode('-', $v['C']);

                    $v['D'] = explode('.', $v['C']);//dump($v['D']);
                    $v['D'] = implode('-', $v['D']);
//                    dump(strtotime($v['C']));
                    $member_info = array(
                        'parent'        => $v['A'],
                        'phone'         => $v['B'],
                        'create_time'   => date('Y-m-d H:i:s', strtotime($v['C'])),
                        'end_time'      => date('Y-m-d H:i:s', strtotime($v['D'])),
                        'times'         => $v['E'],
                        'pay_type'      => 'admin'
                    );
                    $user_id = $this->mem_card_model->add($member_info);
                    if(!$user_id) {
                        $is_commit = false;$error=2;
                        $error = '添加失败';
                        break;
                    }

                }

            }
        }
//        dump($member_info);exit;
        if($is_commit) {
            $this->mem_card_model->commit();
            delFile(getcwd().'/data/upload/excel');
            $this->success('导入成功');
        } else {
            $this->mem_card_model->rollback();
//            echo $error;exit;
            $this->error($error);
        }
//         dump($info);exit;


    }
}